<template>
  <a-modal
    title="编辑标签"
    :width="800"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-bind="formItemLayout" label="标签名称" hasFeedback>
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '名称不能为空' }] }]"
            :maxLength="10"
            placeholder="输入标签名称"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlFindOne, sqlUpdate } from '@/api/sql'
import { mapGetters } from 'vuex'
export default {
  name: 'TagEditeModal',
  data () {
    return {
      id: null,
      confirmLoading: false,
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      form: this.$form.createForm(this),
      result: {}
    }
  },
  created () {},
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  methods: {
    ...mapGetters(['nickname']),

    async init (id) {
      console.log(id)
      this.id = id
      // 显示弹框
      this.visible = true
      this.result = await this.getById(id)
      console.log('result', this.result)
      // 初始化form表单数据
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: this.result.name
        })
      })
    },

    /**
     * cancel
     */
    handleCancel () {
      this.visible = false
    },

    /**
     * submit
     */
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)
        if (!errors) {
          // 检测数据是否存在
          this.verify(values.name).then((res) => {
            console.log(res)
            if (res.id) {
              this.$notification['error']({
                message: '提示',
                description: '标签已存在'
              })
              this.confirmLoading = false
            } else {
              console.log('1111')
              this.update(values).then((response) => {
                this.visible = false
                this.confirmLoading = false
                this.$notification['success']({
                  message: '提示',
                  description: '数据新建成功！'
                })
                // 延迟发送事件，解决列表刷新还是老数据的问题
                setTimeout(() => {
                  this.$emit('ok', values)
                }, 1000)
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /**
     * 修改数据
     */
    update (values) {
      console.log(values)
      console.log('values', values)
      var params = {
        sql: `update t_category_tag set name='${values.name}',modify_by='${this.userInfo.login}' where id=${this.result.id}`
      }
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /**
     * 检测数据标签名称是否重复
     */
    verify (name) {
      const params = {
        sql: `select * from t_category_tag where name='${name}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 获取一条数据
     */
    getById (id) {
      const params = {
        sql: `select * from t_category_tag where id=${id}`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
